package com.aiyige.page.my.merchandisemanagement;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.apiengine.ModuleEngine;
import com.aiyige.base.api.apiengine.OrderEngine;
import com.aiyige.base.db.dao.LearnVideoModelDao;
import com.aiyige.base.db.dao.MajorCourseDBModelDao;
import com.aiyige.base.db.table.LearnVideoModel;
import com.aiyige.base.db.table.MajorCourseDBModel;
import com.aiyige.base.db.table.TraingCardDBModel;
import com.aiyige.base.db.table.TraingClassDBModel;
import com.aiyige.base.eventbus.EventServerChangeMomentStatus;
import com.aiyige.model.Page;
import com.aiyige.model.moment.backup.TagBackup;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.detail.DetailPage;
import com.aiyige.page.my.merchandisemanagement.adapter.MMAdapter;
import com.aiyige.page.my.merchandisemanagement.mmlearnvideo.adapter.MMLearnVideoAdapter;
import com.aiyige.page.my.merchandisemanagement.mmmajorcourse.adapter.MMMajorCourseAdapter;
import com.aiyige.page.my.merchandisemanagement.mmtraingcard.adapter.MMTraingCardAdapter;
import com.aiyige.page.my.merchandisemanagement.mmtraingclass.adapter.MMTraingClassAdapter;
import com.aiyige.page.my.merchandisemanagement.model.TabItem;
import com.aiyige.page.publish.selectinterest.model.PublishIndustryItem;
import com.aiyige.page.publish.selectinterest.model.PublishInterestItem;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.HighLightWordUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.AutoRefreshCommonDataView;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;

@Route(path = ARouterConfig.MMSearchMorePage)
public class MMSearchMorePage extends BaseActivity implements CommonDataView.RetrofitStub, AutoRefreshCommonDataView.Callback {
    public static final String TAG = MMSearchMorePage.class.getSimpleName();
    @BindView(R.id.inputEt)
    EditText inputEt;
    @BindView(R.id.cdv)
    AutoRefreshCommonDataView cdv;
    @Autowired
    int type;
    @Autowired
    String keyword;
    volatile boolean shouldRefresh = true;
    MMAdapter searchAdapter;
    @BindView(R.id.inputEtClearBtn)
    ImageView inputEtClearBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_mmsearch_more);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        setAutoRegisterEventBus(true);
        initAdapter();
        cdv.config(searchAdapter, this);
        cdv.setCallback(this);

        inputEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                inputEtClearBtn.setVisibility(s.length() == 0 ? View.INVISIBLE : View.VISIBLE);
            }
        });
        inputEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    shouldRefresh = true;
                    keyword = inputEt.getText().toString().trim();
                    cdv.refresh();
                    return true;
                }
                return false;
            }
        });
        inputEt.setText(keyword);
        cdv.doRefreshRequest();
    }


    private void initAdapter() {
        searchAdapter = new MMAdapter(this);
        searchAdapter.setEnableHighlight(true);
        searchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MultiItemEntity entity = searchAdapter.getItem(position);
                switch (entity.getItemType()) {
                    case PublishUtil.PARENT_TYPE_LEARN_VIDEO: {
                        LearnVideoModel learnVideoModel = (LearnVideoModel) searchAdapter.getItem(position);
                        switch (learnVideoModel.getProgressStatus()) {
                            case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                                ToastX.show(R.string.server_transcoding);
                                break;
                            default:
                                Router.start(learnVideoModel.getRouter());
                                break;
                        }
                        break;
                    }
                    case PublishUtil.PARENT_TYPE_MAJOR_COURESE: {
                        MajorCourseDBModel majorCourseDBModel = (MajorCourseDBModel) searchAdapter.getItem(position);
                        switch (majorCourseDBModel.getProgressStatus()) {
                            case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                                ToastX.show(R.string.server_transcoding);
                                break;
                            default:
                                Router.start(majorCourseDBModel.getRouter());
                                break;
                        }
                        break;
                    }
                }
            }
        });
    }


    @OnClick({R.id.cancelLayout, R.id.inputEtClearBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cancelLayout:
                finish();
                break;
            case R.id.inputEtClearBtn:
                inputEt.setText("");
                break;
        }
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        Call<ResponseBody> call = null;
        switch (type) {
            case PublishUtil.PARENT_TYPE_LEARN_VIDEO:
                call = ApiManager.getService()
                        .searchMoment(ModuleEngine.COMMODITY_MANAGER, OrderEngine.LATEST, Arrays.asList(Moment.SUBJECT_VIDEO_COURSE), keyword, 15, currentPage);
                break;
            case PublishUtil.PARENT_TYPE_MAJOR_COURESE:
                call = ApiManager.getService()
                        .searchMoment(ModuleEngine.COMMODITY_MANAGER, OrderEngine.LATEST, Arrays.asList(Moment.SUBJECT_MAJOR_COURSE), keyword, 15, currentPage, 1);
                break;
            case PublishUtil.PARENT_TYPE_TRAING_CLASS:
                call = ApiManager.getService()
                        .searchMoment(ModuleEngine.COMMODITY_MANAGER, OrderEngine.LATEST, Arrays.asList(Moment.SUBJECT_TRAINING_COURSE), keyword, 15, currentPage);
                break;
            case PublishUtil.PARENT_TYPE_TRAING_CARD:
                call = ApiManager.getService()
                        .searchMoment(ModuleEngine.COMMODITY_MANAGER, OrderEngine.LATEST, Arrays.asList(Moment.SUBJECT_TRAINING_CARD), keyword, 15, currentPage);
                break;
        }
        shouldRefresh = false;
        return call;
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        switch (type) {
            case PublishUtil.PARENT_TYPE_LEARN_VIDEO:
                return handleLearnVideoResponse(respJson, resultList);
            case PublishUtil.PARENT_TYPE_MAJOR_COURESE:
                return handleMajorCourseResponse(respJson, resultList);
            case PublishUtil.PARENT_TYPE_TRAING_CLASS:
                return handleTraingClassResponse(respJson, resultList);
            case PublishUtil.PARENT_TYPE_TRAING_CARD:
                return handleTraingCardResponse(respJson, resultList);
            default:
                return null;
        }
    }

    private CommonDataView.HandleResult handleMajorCourseResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }
            for (Moment moment : momentList) {
                Moment record = new Moment(moment);
                MajorCourseDBModel majorCourseDBModel = MajorCourseDBModel.parse(record);
                majorCourseDBModel.setTitle(HighLightWordUtil.highLight(record.getTitle(), keyword));
                resultList.add(majorCourseDBModel);
            }
            return new CommonDataView.HandleResult(page.isLast());

        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    private CommonDataView.HandleResult handleTraingClassResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }
            for (Moment moment : momentList) {
                Moment record = new Moment(moment);
                TraingClassDBModel traingClassDBModel = TraingClassDBModel.parse(record);
                traingClassDBModel.setTitle(HighLightWordUtil.highLight(record.getTitle(), keyword));
                resultList.add(traingClassDBModel);
            }
            return new CommonDataView.HandleResult(page.isLast());

        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    private CommonDataView.HandleResult handlePersonalTrainerResponse(String respJson, List resultList) {
        return null;
    }

    private CommonDataView.HandleResult handleTraingCardResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }
            for (Moment moment : momentList) {
                Moment record = new Moment(moment);
                TraingCardDBModel traingCardDBModel = TraingCardDBModel.parse(record);
                traingCardDBModel.setTitle(HighLightWordUtil.highLight(record.getTitle(), keyword));
                resultList.add(traingCardDBModel);
            }
            return new CommonDataView.HandleResult(page.isLast());

        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    private CommonDataView.HandleResult handleUniversalProductResponse(String respJson, List resultList) {
        return null;
    }

    private CommonDataView.HandleResult handleLearnVideoResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }
            for (Moment moment : momentList) {
                Moment record = new Moment(moment);
                LearnVideoModel learnVideoModel = LearnVideoModel.parse(record);
                learnVideoModel.setTitle(HighLightWordUtil.highLight(record.getTitle(), keyword));
                resultList.add(learnVideoModel);
            }
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClearRequestState() {
        if (shouldRefresh) {
            cdv.refresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventServerChangeMomentStatus event) {
        if (TextUtils.isEmpty(event.getMomentId())) return;
        if (event.getSubject().equals(Moment.SUBJECT_MAJOR_COURSE) || event.getSubject().equals(Moment.SUBJECT_VIDEO_COURSE)) {
            int progressStatus;
            switch (event.getTargetStatus()) {
                case Moment.STATUS_IN_REVIEW:
                    progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                    break;
                case Moment.STATUS_REJECT:
                    progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                    break;
                case Moment.STATUS_PUT_ON:
                    progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                    break;
                case Moment.STATUS_SAVE:
                    progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                    break;
                case Moment.STATUS_REVIEW_PASSED:
                    progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                    break;
                case Moment.STATUS_GET_OFF:
                    progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                    break;
                case Moment.STATUS_TRANSCODING:
                    progressStatus = PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                    break;
                default:
                    progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                    break;
            }


            int upLimit = searchAdapter.getData().size();
            for (int i = 0; i < upLimit; ++i) {
                MultiItemEntity entity = searchAdapter.getItem(i);
                switch (entity.getItemType()) {
                    case PublishUtil.PARENT_TYPE_LEARN_VIDEO: {
                        LearnVideoModel learnVideoModel = (LearnVideoModel) entity;
                        if (event.getMomentId().equals(learnVideoModel.getGoodsId())) {
                            learnVideoModel.setProgressStatus(progressStatus);
                            learnVideoModel.setRejectReason(event.getMessage());
                            try {
                                LearnVideoModelDao.getDao().update(learnVideoModel);
                            } catch (Exception e) {
                            }
                            searchAdapter.setData(i, learnVideoModel);
                            return;
                        }
                        break;
                    }
                    case PublishUtil.PARENT_TYPE_MAJOR_COURESE: {
                        MajorCourseDBModel majorCourseDBModel = (MajorCourseDBModel) entity;
                        if (event.getMomentId().equals(majorCourseDBModel.getGoodsId())) {
                            majorCourseDBModel.setProgressStatus(progressStatus);
                            majorCourseDBModel.setRejectReason(event.getMessage());
                            try {
                                MajorCourseDBModelDao.getDao().update(majorCourseDBModel);
                            } catch (Exception e) {
                            }
                            searchAdapter.setData(i, majorCourseDBModel);
                            return;
                        }
                        break;
                    }
                }
            }
        }
    }
}
